# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_CIDR.py 
@time: 2019/7/11 下午3:22
"""
'''
通过 CIDR 地址生成对应的 IP 地址集
ERROR:
ValueError: 10.120.20.64/22 has host bits set
当出现报ip地址值错误，是网络地址的子网掩码规划不正确,也可能通过以下办法解决
ipaddress.ip_network('10.120.20.64/22', False)
'''
import ipaddress

net = ipaddress.ip_network('192.168.1.2/31', False)
print(net)
for a in net:
    print(a)

print('ip6')
net6 = ipaddress.ip_network('12:3456:78:90ab:cd:ef01:23:30/125', False)
print(net6)
for a in net6:
    print(a)

print('取索引值')
net6.num_addresses
print(net6[0])
print(net6[1])
print('网络ip地址验证')
net6_a = ipaddress.ip_address('12:3456:78:90ab:cd:ef01:23:30')
print('(%s) %s %s' %(net6_a, (lambda x:'是在' if x in net6 else '没有在')(net6_a), net6))
net6_b = ipaddress.ip_address('13:3456:78:90ab:cd:ef01:23:30')
print('(%s) %s %s' %(net6_b, (lambda x:'是在' if x in net6 else '没有在')(net6_b), net6))

print('ip地址和网络地址能通过一个IP接口指定')
inet = ipaddress.ip_interface('10.120.21.23/27')
print(inet.netmask)
print(inet.network)
print(inet.ip)

print('IPv4Address是个实例，不是地址字符串，要想使用需要str()进行转换，例如：')
from socket import socket, AF_INET, SOCK_STREAM
s = socket(AF_INET, SOCK_STREAM)
a = ipaddress.ip_address('10.120.21.192')
s.connect((str(a), 20000))
for i in range(10):
    s.send(b'hello ipaddress!'+ str(a).encode('utf-8'))
    print(s.recv(8192).decode('utf-8'))
s.close()
